from django.http import JsonResponse
from django.views import View
from rest_framework import status
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.response import Response
from rest_framework_jwt.utils import jwt_decode_handler

from question.models import Label
from question.serializers.labels import LabelsSerializer, LabelsIDSerializer
from question.utils import get_user_dict
from users.models import User


class LabelsView(ListAPIView):
    """所有标签列表"""
    serializer_class = LabelsSerializer
    queryset = Label.objects.all().order_by('id')


# 用户关注的标签
class LabelsUsersView(ListAPIView):
    serializer_class = LabelsSerializer

    def get_queryset(self):
        # 获取token
        token = self.request.auth

        # 是否为合法请求
        if token:
            # 获取用户信息
            user_dict = jwt_decode_handler(token=token)

            # 用户合法
            if user_dict:
                # 获取用户
                user = User.objects.get(id=user_dict['user_id'])
                # 获取用户关注的标签
                return user.labels.all()


# 关注标签
class LabelsIdFocusinView(View):
    def put(self, request, id):
        # 获取用户信息
        user_dict = get_user_dict(request)

        # 判断用户是否合法
        if user_dict:
            # 获取用户
            user = User.objects.get(id=user_dict['user_id'])
        else:
            return JsonResponse({'message': '未登录', 'success': False})

        try:
            label = Label.objects.get(id=id)
            # 添加
            label.users.add(user)
        except Exception as e:
            return JsonResponse({'message': '数据库查询错误', 'success': False})

        return JsonResponse({'message': 'ok', 'success': True})


# 取消关注标签
class LabelsIdFocusoutView(View):
    def put(self, request, id):
        # 获取用户信息
        user_dict = get_user_dict(request)

        # 判断用户是否合法
        if user_dict:
            # 获取用户
            user = User.objects.get(id=user_dict['user_id'])
        else:
            return JsonResponse({'message': '未登录', 'success': False})

        try:
            label = Label.objects.get(id=id)
            # 删除
            label.users.remove(user)
        except Exception as e:
            return JsonResponse({'message': '数据库查询错误', 'success': False})

        return JsonResponse({'message': 'ok', 'success': True})


# 标签详情
class LabelsIDView(RetrieveAPIView):
    serializer_class = LabelsIDSerializer
    queryset = Label.objects.all()

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)

        # 获取系列化数据
        data_dict = serializer.data
        # 获取图片地址
        url = data_dict['label_icon']
        # 重构图片地址
        url = url.replace(f'8000/labels/{data_dict["id"]}/', '8888/')

        # 修改地址
        data_dict['label_icon'] = url
        return Response(data_dict)
